import React from 'react';
import { Table, message, Popconfirm, Button } from 'antd';
import { getUser, deleteUser } from '@/services/user';
import { useAccess } from '@umijs/max';
const User = () => {
  //存放用户的数据
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const access = useAccess();


  const fetchUsers = async () => {
    setLoading(true);
    try {
      const { list } = await getUser();
      setData(list);
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  }
  React.useEffect(() => {
    fetchUsers();
  }, []);
  const columns: any = [
    {
      title: '用户名',
      dataIndex: 'username'
    }
  ]
  if (access.canReadUserPassword) {
    columns.push({
      title: '密码',
      dataIndex: 'password'
    });
  }
  const handleDelete = async (id) => {
    try {
      await deleteUser([id]);
      message.success('删除成功');
      fetchUsers();
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  }
  if (access.canDeleteUser) {
    columns.push({
      title: '操作',
      render: (_, record) => {
        return (
          <Popconfirm title="确定要删除吗?" onConfirm={() => handleDelete(record.id)}>
            <Button type="primary">删除</Button>
          </Popconfirm>
        )
      }
    });
  }
  return (
    <Table
      rowKey={"id"}
      columns={columns}
      dataSource={data}
      loading={loading}
    />
  )
}
export default User;